package org.example.myleet.p441;

public class Solution {
    public int arrangeCoins(int n) {
        if (n == 1) {
            return 1;
        }
        long l = 0, r = n, m, sum;
        while (r - l > 1) {
            m = (r + l) / 2;
            sum = m * (m + 1) / 2;
            if (sum > n) {
                r = m;
            } else if (sum < n) {
                l = m;
            } else {
                return (int) m;
            }
        }
        sum = r * (r + 1) / 2;
        if (sum < n) {
            return (int) r;
        }
        return (int) l;
    }
}
